package com.lsa.letcode.the147.insertionSortList;

import com.lsa.letcode.common.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode n) {
    	if (n == null) {
    		return null;
    	}
    	
    	ListNode sorted = null;
    	while(n != null){
    		ListNode next = n.next;
    		sorted = merge(sorted, n);
			n = next;
    	}
    	
    	return sorted;
    }
    
    public ListNode sortList(ListNode head) {
    	return insertionSortList(head);
    }

	private ListNode merge(ListNode cur, ListNode n) {
		ListNode prev = null;
		ListNode head = cur;
		while(cur != null && cur.val < n.val) {
			prev = cur;
			cur = cur.next;
		}
		if (prev != null){ 
			// insert 'n' after 'prev'
			ListNode tmp = prev.next;
			prev.next = n;
			n.next = tmp;
		}
		else {
			// insert 'n' before 'head'
			n.next = head;
			head = n;
		}
		return head;
	}
}